<template>
  <div>
    <el-row>
      <el-button type="success" icon="circle-plus"  @click="addBtn">添加</el-button>
      <el-button type="primary" icon="setting" @click="openBindPermission" :disabled="!defaultRow">权限赋予</el-button>
      <el-button type="danger" icon="setting" @click="openBindMenu" :disabled="!defaultRow">菜单赋予</el-button>
      <!-- 批量操作 -->
    </el-row>
    <qa-table ref="tableRef" :action="table.action" :columns="table.columns"
      :right-btns="['detail_auto', 'update', 'delete']" size="default" @current-change="currentChange" :border="true"
      @update="updateBtn" @delete="deleteBtn" :row-no="true"></qa-table>

    <qa-dialog :title="form.props.title" v-model="form.props.show" v-slot="slotProps">
      <qa-form v-model="form.data" :rules="form.props.rules" :columns="form.props.columns" mode="form"
        :closeDialog="slotProps.closeDialog" :labelWidth="100" :action="form.props.action"
        :formType="form.props.formType" @success="form.props.show = false; tableRef?.refresh()"></qa-form>
    </qa-dialog>

  </div>
</template>

<script setup lang="ts">
import qaTable from '@/components/qa-table.vue'
import qaDialog from '@/components/qa-dialog.vue';
import qaForm from '@/components/qa-form.vue';
import bindMenu from './form/bindMenu.vue';
import bindPermission from './form/bindPermission.vue';
const originalForms: any = {}; // 表单初始化数据

const tableRef = ref<InstanceType<typeof qaTable> | null>(null);
const table = ref({
  action: '/admin/system/sysRole/systemRole/getList',
  columns: [
    {
      key: "role_id",
      title: "角色标识",
      type: "text",
      align: "left",

    },
    {
      key: "role_name",
      title: "角色名称",
      type: "text",
      align: "left"
    },
    {
      key: "comment",
      title: "备注",
      type: "text",
      align: "left"
    },
    {
      key: "permissionList",
      title: "拥有权限",
      type: "text",
      formatter:(val: any, row: any, column: any, index: number)=>{
        let str = "";
          if(row.role_id === "admin"){
            str = "系统内置角色 - 拥有所有权限";
          }else if(val === null || val === undefined || val.length <= 0){
            str = "该角色未赋予任何权限";
          }else{
            val.map((item: any, index: number) => {
                str += item.permission_name;
                if (index !== val.length - 1) {
                  str += "、";
                }
            });
          }
          return str;
      },
      align: "left"
    },
    {
      key: "menuList",
      title: "拥有菜单",
      type: "text",
      formatter:(val, row, column, index)=>{
        let str = "";
          if(row.role_id === "admin"){
            str = "系统内置角色 - 拥有所有菜单";
          }else if(val === null || val === undefined || val.length <= 0){
            str = "该角色未赋予任何菜单";
          }else{
            val.map((item: any, index: number) => {
                str += item.title;
                if (index !== val.length - 1) {
                  str += "、";
                }
            });
          }
          return str;
      },
      align: "left"
    },
  ]
})

const defaultRow = ref(null)
const currentChange = (row: any) => {
  console.log('选中项', row)
  defaultRow.value = row
}

const form = ref({
  data: {
    parent_id: null,
    menu_id: "",
    menu:[],
    permission:[],
  },
  props: {
    title: "",
    action: "",
    columns: [
      {
        key: "role_name",
        title: "角色名称",
        type: "text",
        align: "left",
      },

      {
        key: "role_id",
        title: "角色标识",
        type: "text",
        align: "left",
      },
      {
        key: "comment",
        title: "备注",
        type: "text",
        align: "left",
      }
    ],
    rules: {

    },
    formType: 'add' as 'add' | 'update',
    show: false
  }
})

interface formDatas {
  show: boolean;
  data: {
    [key: string]: any; // 动态键名，值为 any 类型
  };
}
const formDatas = ref<formDatas>({
  show: false,
  data: {}
})

originalForms['data'] = JSON.parse(JSON.stringify(form.value.data));

const openBindMenu = () => {
  const container = document.createElement('div');
  document.body.appendChild(container);

  formDatas.value.show = true; // 确保对话框初始状态为 true
  if (defaultRow.value) {
    formDatas.value.data = defaultRow.value;
  }
  const appInstance = createApp({
    render() {
      return h(bindMenu, {
        modelValue: formDatas.value, // 传递布尔值
        close: (value: any) => {
          formDatas.value.show = false;
          if (container.parentNode) {
            setTimeout(()=>{
              appInstance.unmount(); // 卸载 Vue 应用
              document.body.removeChild(container); // 移除 DOM 节点
            },500)
          }
        },
      });
    },
  });

  appInstance.mount(container);
};

// 函数形式调用qa-form
const openBindPermission = () => {
  const container = document.createElement('div');
  document.body.appendChild(container);

  formDatas.value.show = true; // 确保对话框初始状态为 true
  if (defaultRow.value) {
    formDatas.value.data = defaultRow.value;
  }
  const appInstance = createApp({
    render() {
      return h(bindPermission, {
        modelValue: formDatas.value, // 传递布尔值
        close: (value: any) => {
          formDatas.value.show = false;
          if (container.parentNode) {
            setTimeout(()=>{
              appInstance.unmount(); // 卸载 Vue 应用
              document.body.removeChild(container); // 移除 DOM 节点
            },500)
          }
        },
      });
    },
  });

  appInstance.mount(container);
};


const addBtn = () => {
  form.value.data = { ...originalForms['data'] }
  form.value.props.action = '/admin/system/sysRole/systemRole/add';
  form.value.props.formType = "add"
  form.value.props.title = '添加';
  form.value.props.show = true
}

const deleteBtn = (row: any, deleteFn: (params: { action: string, data: any }) => Promise<void>) => {
  deleteFn({
    action: '/admin/system/sysRole/systemRole/delete',
    data: {
      _id: row._id
    }
  })
}
const updateBtn = (row: any) => {
  form.value.data = row
  form.value.props.action = '/admin/system/sysRole/systemRole/update';
  form.value.props.formType = "update"
  form.value.props.title = '编辑';
  form.value.props.show = true
}

const search = () => {
  if (tableRef.value) {
    (tableRef.value as { Search: () => void }).Search();
  }
}
</script>

<style scoped></style>
